<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>朋友圈页面</title>
    <link rel="stylesheet" href="./font/iconfont.css">
    <link rel="stylesheet" href="./css/pyq.css">
</head>
<body>
  <div class="container">
      <div class="top">
          <div class="nav">
              <span onclick="back()" class="top-icon iconfont icon-fanhui"></span>
              <span onclick="shuaxin()" class="top-icon iconfont icon-shuaxin"></span>
              <div style="display: flex;align-items: center;margin-left: auto">
                  <img onclick="publish()" style="cursor: pointer;padding: 6px;width: 20px;height: fit-content" src="./img/camera.png">
                  <span class="top-icon iconfont icon-tixing"></span>
                  <span onclick="guanbi()" class="top-icon iconfont icon-guanbi"></span>
              </div>
          </div>
          <div class="user">
              <div id="username"></div>
              <img class="user-icon" src="./favicon.ico">
          </div>
      </div>

      <div class="pyq-list">
<!--          <div class="pyq-item">-->
<!--              <img class="pyq-icon" src="./favicon.ico">-->
<!--              <div class="pyq">-->
<!--                  <div class="content-username">-->
<!--                      暮岁壹拾(小红书宿舍)-->
<!--                  </div>-->
<!--                  <div class="content">-->
<!--                      感谢小伙伴的支持认可，老韩都是本着良心做事情，无论是书籍内容还是印刷质量，我都要求做到最好，这样也能对得起同学们对我的期待！-->
<!--                  </div>-->
<!--                  <div class="content-bottom">-->
<!--                      <img src="./img/comment.png">-->
<!--                      <img class="like" onclick="like(this,this.parentNode.parentNode.parentNode)" src="./img/like.png">-->
<!--                      <div class="date">-->
<!--                          2024年2月11日 20:00-->
<!--                      </div>-->
<!--                  </div>-->
<!--                  <div class="area">-->
<!--                      <div class="love-area small-area">-->
<!--                          <img class="love-img" src="./img/love.png">-->
<!--                      </div>-->

<!--                  </div>-->
<!--              </div>-->
<!--          </div>-->

      </div>



  </div>
</body>
</html>
<script src="./js/pyq.js"></script>
<script>


    var USERNAME = localStorage.getItem("username");
    document.getElementById('username').innerText = USERNAME
    function send(element,pyqItem) {
        const text = pyqItem.querySelector('textarea').value.trim();
        const commentArea = pyqItem.querySelector('.comment-area');
        if (text !== ''){
            commentArea.style.display = 'block';
            commentArea.innerHTML += `
                                    <div class="comment">
                                      <span class="comment-user">${USERNAME}</span>
                                   :
                                      <span class="comment-content"> ${text}</span>
                                  </div>`
        }
        pyqItem.querySelector('textarea').value = '';
        hidden1(element);

        // 构造请求对象
        const commentData = {
            username: USERNAME,
            pyqId: event.target.closest('.pyq-item').dataset.pyqId,
            content: text
        };


        fetch('http://localhost/pyq/addComment', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': localStorage.getItem("token")
            },
            body: JSON.stringify(commentData)
        }).then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json(); // 解析响应的JSON数据
        })
            .then(data => {
                if (data.flag) {
                    console.log('评论成功');
                }else {
                    console.log('评论失败');
                }
            })
            .catch(error => {
                // 处理请求过程中的错误
                console.error('请求出现问题:', error);

            });
    }
    function hidden1(element) {
        setTimeout(function() {
            element.style.display = 'none';
        }, 200);
    }

    function handleInput(event,element) {
        const textarea = element.querySelector('textarea');
        const sendButton = element.querySelector('button');

        if (textarea.value.trim() === '') {
            sendButton.style.cursor = '';
            sendButton.style.backgroundColor = '#e7e7e8';
            sendButton.style.color = '#989898';
        } else {
            sendButton.style.cursor = 'pointer';
            sendButton.style.backgroundColor = '#02c55e'; // 恢复按钮的默认背景色
            sendButton.style.color = 'white'; // 恢复按钮的默认文字颜色
        }

    }

    function handleKeyDown(event,element) {
        const textarea = element.querySelector('textarea');
        if(event.keyCode === 13){
            event.preventDefault();
            if ( textarea.value.trim() !== '') {
                send(element,element.parentNode.parentNode);
            }
        }

    }



    fetch('http://localhost/pyq/getPyqList', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': localStorage.getItem("token")
            },
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                if (data.flag) {
                    var dataFromBackend = data.data;
                    // 获取朋友圈列表容器
                    const pyqList = document.querySelector('.pyq-list');

                    // 遍历数据，创建朋友圈条目并添加到朋友圈列表容器中
                    dataFromBackend.forEach(dataItem => {


                        const pyqItem = document.createElement('div');
                        pyqItem.classList.add('pyq-item');
                        pyqItem.dataset.pyqId = dataItem.id; // 将朋友圈的id 嵌入到元素的自定义数据属性中
                        var flag = false;
                        dataItem.likes.forEach(v => {
                                if (USERNAME == v.username) {
                                    flag = true;
                                }
                            }
                        )
                        if (flag) {
                            pyqItem.innerHTML = `
                                <img class="pyq-icon" src="./favicon.ico">
                                <div class="pyq">
                                    <div class="content-username">${dataItem.username}</div>
                                    <div class="content">${dataItem.content}</div>
                                    <div class="content-bottom">
                                        <img onclick="comment(this.parentNode.parentNode.parentNode)" src="./img/comment.png">
                                        <img class="like" onclick="like(this,this.parentNode.parentNode.parentNode)" src="./img/like_.png">
                                        <div class="date">${dataItem.date}</div>
                                    </div>
                                    <div class="area">
                                        <div class="love-area small-area">
                                            <img class="love-img" src="./img/love.png">
                                        </div>
                                        <div class="comment-area small-area"></div>
                                        <div class="small-area input-area" onkeydown="handleKeyDown(event,this)" oninput="handleInput(event,this)">
                                            <textarea onblur="hidden1(this.parentNode)" placeholder="评论"></textarea>
                                            <button onclick="send(this.parentNode,this.parentNode.parentNode.parentNode)" class="send-button">
                                                发送
                                            </button>
                                        </div>

                                    </div>
                                </div>
                            `;
                        }else {
                            pyqItem.innerHTML = `
                                <img class="pyq-icon" src="./favicon.ico">
                                <div class="pyq">
                                    <div class="content-username">${dataItem.username}</div>
                                    <div class="content">${dataItem.content}</div>
                                    <div class="content-bottom">
                                        <img onclick="comment(this.parentNode.parentNode.parentNode)" src="./img/comment.png">
                                        <img class="like" onclick="like(this,this.parentNode.parentNode.parentNode)" src="./img/like.png">
                                        <div class="date">${dataItem.date}</div>
                                    </div>
                                    <div class="area">
                                        <div class="love-area small-area">
                                            <img class="love-img" src="./img/love.png">
                                        </div>
                                        <div class="comment-area small-area"></div>
                                        <div class="small-area input-area" onkeydown="handleKeyDown(event,this)" oninput="handleInput(event,this)">
                                            <textarea onblur="hidden1(this.parentNode)" placeholder="评论"></textarea>
                                            <button onclick="send(this.parentNode,this.parentNode.parentNode.parentNode)" class="send-button">
                                                发送
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            `;
                        }


                        // 获取点赞列表区域并渲染点赞者列表
                        const loveArea = pyqItem.querySelector('.love-area');
                        dataItem.likes.forEach((liker, index) => {
                            if (index !== 0) {
                                loveArea.innerHTML += '<span style="color: black">，</span>';
                            }
                            loveArea.innerHTML += `<span>${liker.username}</span>`;
                        });

                        // 如果点赞列表为空，隐藏点赞区域
                        if (dataItem.likes.length == 0) {
                            loveArea.style.display = 'none';
                        }

                        // 获取评论列表区域并渲染评论者列表
                        const commentArea = pyqItem.querySelector('.comment-area');
                        dataItem.comments.forEach((comment) => {
                            commentArea.innerHTML += `
                                    <div class="comment">
                                      <span class="comment-user">${comment.username}</span>
                                   :
                                      <span class="comment-content"> ${comment.content}</span>
                                  </div>
                            `
                        });

                        // 如果评论列表为空，隐藏点赞区域
                        if (dataItem.comments.length == 0) {
                            commentArea.style.display = 'none';
                        }
                        // 将朋友圈条目添加到朋友圈列表容器中
                        pyqList.appendChild(pyqItem);
                    });
                }else {

                }
            })
            .catch(error => {
                console.error('请求出现问题:', error);
                alert('您尚未登录，请先登录！');
                localStorage.clear();
                window.location.href = 'login.html'
            });

    // var commentArea = pyqItem.querySelector('.comment-area');

    function comment(pyqItem) {
        var inputArea = pyqItem.querySelector('.input-area');
        inputArea.style.display = "block";
        pyqItem.querySelector('textarea').focus();

    }


    function like(element,pyqItem) {
        const username = USERNAME; // 从 localStorage 获取用户名 todo

        if (element.src.includes("like.png")) {
            element.src = "./img/like_.png";
            const loveArea = pyqItem.querySelector('.love-area');
            const likerElement = document.createElement('span');
            likerElement.textContent = username;

            const validChildNodesCount = Array.from(loveArea.childNodes).filter(node => node.nodeType === Node.ELEMENT_NODE).length;

            if (validChildNodesCount > 1) {
                // 如果已经有点赞者，则添加逗号分隔符
                const separator = document.createElement('span');
                separator.innerText = "，";
                separator.className = 'black';
                loveArea.appendChild(separator);
            }


            loveArea.appendChild(likerElement);
            loveArea.style.display = 'flex';

            // 构造请求对象
            const addLikeData = {
                username: USERNAME,
                pyqId: event.target.closest('.pyq-item').dataset.pyqId
            };
            // 发送POST请求来添加点赞信息，参数就两个一个是这个朋友圈的id 一个就是自身的username
            fetch('http://localhost/pyq/addLike', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': localStorage.getItem("token")
                },
                body: JSON.stringify(addLikeData)
            }).then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json(); // 解析响应的JSON数据
            })
            .then(data => {
                if (data.flag) {
                    console.log('点赞成功');
                }else {
                    console.log('点赞失败');
                }
            })
            .catch(error => {
                // 处理请求过程中的错误
                console.error('请求出现问题:', error);

            });

        } else {
            element.src = "./img/like.png";
            // 获取点赞列表区域
            const loveArea = pyqItem.querySelector('.love-area');

            // 获取所有点赞者元素
            const likers = loveArea.querySelectorAll('span');

            // 查找并移除当前用户的点赞者元素
            for (let i = 0; i < likers.length; i++) {
                const liker = likers[i];
                if (liker.textContent === username) {
                    loveArea.removeChild(liker);
                    if (i > 0) {
                        loveArea.removeChild(likers[i-1]);
                    }
                }
            }

            const validChildNodesCount = Array.from(loveArea.childNodes).filter(node => node.nodeType === Node.ELEMENT_NODE).length;
            // 如果点赞列表为空，隐藏点赞区域
            if (validChildNodesCount == 1) {
                loveArea.style.display = 'none';
            }

            // 构造请求对象
            const deleteLikeData = {
                username: USERNAME,
                pyqId: event.target.closest('.pyq-item').dataset.pyqId
            };

            // 发送DELETE请求来删除点赞信息，参数就两个一个是这个朋友圈的id 一个就是自身的username
            fetch('http://localhost/pyq/deleteLike', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': localStorage.getItem("token")
                },
                body: JSON.stringify(deleteLikeData)
            }).then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json(); // 解析响应的JSON数据
            })
                .then(data => {
                    if (data.flag) {
                        console.log('取消点赞成功');
                    }else {
                        console.log('取消点赞失败');
                    }
                })
                .catch(error => {
                    // 处理请求过程中的错误
                    console.error('请求出现问题:', error);
                });
        }

        element.classList.add('enlarged');
        setTimeout(() => {
            element.classList.remove('enlarged');
        }, 400);
    }
</script>
